"""
管理员内容管理视图
"""
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAdminUser
from django.db.models import Q, Count
from django.utils import timezone
from datetime import timedelta
from .models import Post, Comment
from .serializers import PostSerializer, CommentSerializer


class AdminPostViewSet(viewsets.ReadOnlyModelViewSet):
    """管理员动态管理视图集"""
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAdminUser]
    
    def get_queryset(self):
        """获取动态列表，支持搜索和筛选"""
        queryset = Post.objects.select_related('user', 'route_plan').prefetch_related(
            'post_images', 'comments', 'likes'
        ).annotate(
            comments_count=Count('comments'),
            likes_count=Count('likes')
        )
        
        # 搜索
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(content__icontains=search) |
                Q(user__username__icontains=search)
            )
        
        # 筛选最近动态
        recent_only = self.request.query_params.get('recent_only', None)
        if recent_only == 'true':
            seven_days_ago = timezone.now() - timedelta(days=7)
            queryset = queryset.filter(created_at__gte=seven_days_ago)
        
        return queryset.order_by('-created_at')
    
    @action(detail=True, methods=['delete'])
    def delete(self, request, pk=None):
        """删除动态"""
        post = self.get_object()
        post.delete()
        return Response({'message': '动态已删除'})
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取动态统计信息（增强版）"""
        from django.db.models import Avg, Max
        
        total_posts = Post.objects.count()
        seven_days_ago = timezone.now() - timedelta(days=7)
        recent_posts = Post.objects.filter(created_at__gte=seven_days_ago).count()
        
        # 有图片的动态数
        posts_with_images = Post.objects.filter(post_images__isnull=False).distinct().count()
        
        # 有评论的动态数
        posts_with_comments = Post.objects.annotate(
            comments_count=Count('comments')
        ).filter(comments_count__gt=0).count()
        
        # 点赞统计
        posts_with_likes = Post.objects.annotate(
            likes_count=Count('likes')
        ).filter(likes_count__gt=0)
        
        avg_likes = posts_with_likes.aggregate(avg=Avg('likes_count'))['avg'] or 0
        max_likes = posts_with_likes.aggregate(max=Max('likes_count'))['max'] or 0
        
        # 发布趋势（最近7天）
        post_trend = []
        for i in range(7):
            date = timezone.now() - timedelta(days=6-i)
            count = Post.objects.filter(
                created_at__date=date.date()
            ).count()
            post_trend.append({
                'date': date.strftime('%Y-%m-%d'),
                'count': count
            })
        
        return Response({
            'total': total_posts,
            'recent': recent_posts,
            'with_images': posts_with_images,
            'with_comments': posts_with_comments,
            'avg_likes': round(avg_likes, 2),
            'max_likes': max_likes,
            'post_trend': post_trend,
            'engagement_rate': round((posts_with_comments / total_posts * 100) if total_posts > 0 else 0, 2)
        })


class AdminCommentViewSet(viewsets.ReadOnlyModelViewSet):
    """管理员评论管理视图集"""
    queryset = Comment.objects.all()
    serializer_class = CommentSerializer
    permission_classes = [IsAdminUser]
    
    def get_queryset(self):
        """获取评论列表，支持搜索和筛选"""
        queryset = Comment.objects.select_related('user', 'post')
        
        # 搜索
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(content__icontains=search) |
                Q(user__username__icontains=search)
            )
        
        # 筛选最近评论
        recent_only = self.request.query_params.get('recent_only', None)
        if recent_only == 'true':
            seven_days_ago = timezone.now() - timedelta(days=7)
            queryset = queryset.filter(created_at__gte=seven_days_ago)
        
        return queryset.order_by('-created_at')
    
    @action(detail=True, methods=['delete'])
    def delete(self, request, pk=None):
        """删除评论"""
        comment = self.get_object()
        comment.delete()
        return Response({'message': '评论已删除'})
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取评论统计信息"""
        total_comments = Comment.objects.count()
        recent_comments = Comment.objects.filter(
            created_at__gte=timezone.now() - timedelta(days=7)
        ).count()
        
        return Response({
            'total': total_comments,
            'recent': recent_comments
        })








